package org.finesys.common.security.core.config;

import org.finesys.common.security.core.annotation.EnableAuthResourceServer;
import org.finesys.common.security.core.service.impl.RedisOAuth2AuthorizationConsentService;
import org.finesys.common.security.core.service.impl.RedisOAuth2AuthorizationService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

@AutoConfiguration
@Order(value = Ordered.HIGHEST_PRECEDENCE)
@AutoConfigureBefore(value = EnableAuthResourceServer.class)
public class AuthServerRedisConfig {

    @Bean
    public RedisTemplate<String, Object> oauthRedisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        //key序列化
        RedisSerializer<String> keySerializer = RedisSerializer.string();
        //value序列化
        RedisSerializer<Object> valueSerializer = RedisSerializer.java();
        redisTemplate.setKeySerializer(keySerializer);
        redisTemplate.setHashKeySerializer(keySerializer);
        redisTemplate.setValueSerializer(valueSerializer);
        redisTemplate.setHashValueSerializer(valueSerializer);
        return redisTemplate;
    }

    /**
     * redis存储token对象
     */
    @Bean
    @DependsOn(value={"oauthRedisTemplate"})
    RedisOAuth2AuthorizationService redisOAuth2AuthorizationService(@Qualifier(value = "oauthRedisTemplate") RedisTemplate<String, Object> oauthRedisTemplate) {
        return new RedisOAuth2AuthorizationService(oauthRedisTemplate);
    }

    /**
     * redis存储token对象
     */
    @Bean
    @DependsOn(value={"oauthRedisTemplate"})
    RedisOAuth2AuthorizationConsentService redisOAuth2AuthorizationConsentService(@Qualifier(value = "oauthRedisTemplate") RedisTemplate<String, Object> oauthRedisTemplate) {
        return new RedisOAuth2AuthorizationConsentService(oauthRedisTemplate);
    }
}
